﻿using TjZheng.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using TjZheng.Domain.Business;
using TjZheng.Domain.DataEntity;
using System.Web;

namespace TjZheng.Controls
{
    public static class ControlExtension
    {
        /// <summary>
        /// 隐藏域
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">input的name属性</param>
        /// <param name="value">input的value属性</param>
        /// <param name="isShowMinValue">值类型是否显示最小值</param>
        /// <returns></returns>
        public static MvcHtmlString Hidden(this HtmlHelper htmlHelper, string name, object value, bool isShowMinValue)
        {
            if (!isShowMinValue)
            {
                string str = value.ToString();
                if (RegexHelper.IsMatch(str, @"^0+\.{0,1}0*$") || string.Equals(str, Guid.Empty.ToString()))
                {
                    return htmlHelper.Hidden(name, string.Empty);
                }
            }
            return htmlHelper.Hidden(name, value);
        }
        /// <summary>
        /// 清空对应input的name属性的值
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">选中框的标题</param>
        /// <param name="idOrname">Id或者Name选择器</param>
        /// <param name="click">选中事件</param>
        /// <returns></returns>
        public static MvcHtmlString CheckClearValue(this HtmlHelper htmlHelper, string title, string idOrname, string click)
        {
            return MvcHtmlString.Create(string.Format("<input type=\"checkbox\" style=\"margin-top: 6px;\" onclick=\"{0}\" />{1}<input id=\"{2}_temp\" type=\"hidden\" />", click, title, idOrname.Replace(".", "_")));
        }
        /// <summary>
        /// 清空对应input的name属性的值
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="title">选中框的标题</param>
        /// <param name="idOrname">Id或者Name选择器</param>
        /// <returns></returns>
        public static MvcHtmlString CheckClearValue(this HtmlHelper htmlHelper, string title, string idOrname)
        {
            return MvcHtmlString.Create(string.Format("<input type=\"checkbox\" style=\"margin-top: 6px;\" onclick=\"CheckClearValue(this,'{0}');\" />{1}<input id=\"{2}_temp\" type=\"hidden\" />", idOrname, title, idOrname.Replace(".", "_")));
        }
        /// <summary>
        /// CheckBox
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">input的name属性</param>
        /// <param name="value">input的value属性</param>
        /// <param name="checkValue">选中值</param>
        /// <param name="unCheckValue">未选中值</param>
        /// <param name="htmlAttributes">Html属性</param>
        /// <returns></returns>
        public static MvcHtmlString CheckBox(this HtmlHelper htmlHelper, string name, object value, object checkValue, object unCheckValue, object htmlAttributes = null)
        {
            string objCheck = checkValue.ToString();
            string objUnCheck = unCheckValue.ToString();
            if (string.Equals(objCheck, objUnCheck, StringComparison.OrdinalIgnoreCase))
            {
                return MvcHtmlString.Create("<!--选中与未选中值相等-->");
            }
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            string objValue = value.ToString();
            object obj = null;
            if (objHtmlAttributes.TryGetValue("value", out obj))
            {
                objHtmlAttributes.Remove("value");
            }
            if (string.Equals(objCheck, objValue, StringComparison.OrdinalIgnoreCase))
            {
                objHtmlAttributes["checked"] = "checked";
            }
            return MvcHtmlString.Create(string.Format("<input id=\"{0}\" name=\"{1}\" type=\"checkbox\" value=\"{2}\" {3} /><input name=\"{1}\" type=\"hidden\" value=\"{4}\" />", name.Replace(".", "_"), name, checkValue, objHtmlAttributes.Select(keyvalue => string.Format("{0}=\"{1}\"", keyvalue.Key, keyvalue.Value)).JoinString(" "), unCheckValue));
        }
        /// <summary>
        /// CheckBox列表（无空值验证）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">input的name属性</param>
        /// <param name="value">input的value属性</param>
        /// <param name="selectList">CheckBox选项</param>
        /// <param name="htmlAttributes">Html属性</param>
        /// <returns></returns>
        public static MvcHtmlString CheckBoxList(this HtmlHelper htmlHelper, string name, object value, List<SelectListItem> selectList, object htmlAttributes = null)
        {
            if (selectList.IsNull())
            {
                return MvcHtmlString.Create("<!--未设置CheckBox选项-->");
            }
            StringBuilder objStringBuilder = new StringBuilder();
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            objStringBuilder.AppendFormat("<div {0}>", objHtmlAttributes.Select(keyvalue => string.Format("{0}=\"{1}\"", keyvalue.Key, keyvalue.Value)).JoinString(" "));
            string objValue = value.ToString();
            if (objValue.IsNoNull())
            {
                objStringBuilder.AppendFormat("<input id=\"{0}\" type=\"hidden\" name=\"{1}\" value=\"{2}\" />", name.Replace(".", "_"), name, objValue);
                var objValues = objValue.Split(',');
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"checkbox\" onclick=\"SetCheckValue(this);\" value=\"{0}\" {1} />{2}", item.Value, objValues.Contains(item.Value) ? "checked=\"checked\"" : "", item.Text);
                }
            }
            else
            {
                objStringBuilder.AppendFormat("<input id=\"{0}\" type=\"hidden\" name=\"{1}\" value=\"{2}\" />", name.Replace(".", "_"), name, selectList.Select(c => c.Value).JoinString(","));
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"checkbox\" onclick=\"SetCheckValue(this);\" value=\"{0}\" {1} />{2}", item.Value, item.Selected ? "checked=\"checked\"" : "", item.Text);
                }
            }
            objStringBuilder.Append("</div>");
            return MvcHtmlString.Create(objStringBuilder.ToString());
        }
        /// <summary>
        /// RadioButton列表（无空值验证）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="name">input的name属性</param>
        /// <param name="value">input的value属性</param>
        /// <param name="htmlAttributes">Html属性</param>
        /// <param name="selectList">CheckBox选项</param>
        /// <returns></returns>
        public static MvcHtmlString RadioButtonList(this HtmlHelper htmlHelper, string name, object value, List<SelectListItem> selectList, object htmlAttributes = null)
        {
            if (selectList.IsNull())
            {
                return MvcHtmlString.Create("<!--未设置CheckBox选项-->");
            }
            StringBuilder objStringBuilder = new StringBuilder();
            IDictionary<string, object> objHtmlAttributes = htmlAttributes.CreateValueDictionary();
            if (objHtmlAttributes.IsNull())
            {
                objHtmlAttributes = new Dictionary<string, object>();
            }
            objHtmlAttributes["id"] = name.Replace(".", "_");
            objStringBuilder.AppendFormat("<div {0}>", objHtmlAttributes.Select(keyvalue => string.Format("{0}=\"{1}\"", keyvalue.Key, keyvalue.Value)).JoinString(" "));
            string objValue = value.ToString();
            if (objValue.IsNoNull())
            {
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"radio\" name=\"{0}\" value=\"{1}\" {2} />{3}", name, item.Value, string.Equals(objValue, item.Value, StringComparison.OrdinalIgnoreCase) ? "checked=\"checked\"" : "", item.Text);
                }
            }
            else
            {
                foreach (var item in selectList)
                {
                    objStringBuilder.AppendFormat("<input type=\"radio\" name=\"{0}\" value=\"{1}\" {2} />{3}", name, item.Value, item.Selected ? "checked=\"checked\"" : "", item.Text);
                }
            }
            objStringBuilder.Append("</div>");
            return MvcHtmlString.Create(objStringBuilder.ToString());
        }
        /// <summary>
        /// 原生图片上传控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="objUpLoadSet"></param>
        /// <param name="onchange"></param>
        /// <returns></returns>
        public static MvcHtmlString UpLoadNativeImage(this HtmlHelper htmlHelper, UpLoadSet objUpLoadSet, string onchange = "LocalImagePreview(this)")
        {
            BizUploadLimit objBizUploadLimit = new BizUploadLimit();
            UploadLimit objUploadLimit = null;
            if (objUpLoadSet.Name.IsNull())
            {
                return MvcHtmlString.Create("<!--提交到服务器的Name不能为空-->");
            }
            if (objUpLoadSet.ULId > 0)
            {
                objUploadLimit = objBizUploadLimit.GetRecord(objUpLoadSet.ULId);
            }
            else
            {
                if (objUpLoadSet.CategoryCode.IsNoNull() && objUpLoadSet.LimitCode.IsNoNull())
                {
                    objUploadLimit = objBizUploadLimit.GetRecord(string.Format("UcCode='{0}' AND LimitCode='{1}'", objUpLoadSet.CategoryCode, objUpLoadSet.LimitCode));
                }
            }
            if (objUploadLimit == null)
            {
                return MvcHtmlString.Create("<!--未设置上传文件配置-->");
            }
            if (objUploadLimit.UcCode.IsNull() || objUploadLimit.LimitCode.IsNull())
            {
                return MvcHtmlString.Create("<!--上传文件的资源码和限制码不能为空-->");
            }
            StringBuilder objStringBuilder = new StringBuilder();
            string selector = objUpLoadSet.Name.Replace(".", "_");
            objStringBuilder.AppendFormat("<input id=\"{0}_File\" name=\"{1}.File\" type=\"file\" accept=\"{2}\" onchange=\"{3};\" />", selector, objUpLoadSet.Name, objUploadLimit.LimitExtension.Replace("*", "").Replace(".", "").Replace(" ", "").Split(';').Select(c => c.FormatSelf("image/{0}")).JoinString(","), onchange);
            objStringBuilder.AppendFormat("<input id=\"{0}\" name=\"{1}\" type=\"hidden\" value=\"{2}\" />", selector, objUpLoadSet.Name, objUpLoadSet.Value);
            objStringBuilder.AppendFormat("<input id=\"{0}_Set\" name=\"{1}.Set\" type=\"hidden\" value='{{\"ULId\":\"{2}\",\"CategoryCode\":\"{3}\",\"LimitCode\":\"{4}\",Name:\"{5}\",\"ServerPath\":\"{5}\"}}' />", selector, objUpLoadSet.Name, objUploadLimit.Id, objUploadLimit.UcCode, objUploadLimit.LimitCode, objUpLoadSet.Name, objUploadLimit.ServerPath);
            return MvcHtmlString.Create(objStringBuilder.ToString());
        }
        /// <summary>
        /// 原生图片上传控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="ulid">限制码Id</param>
        /// <param name="name">隐藏的Name属性</param>
        /// <param name="value">隐藏的Value值</param>
        /// <param name="onchange"></param>
        /// <returns></returns>
        public static MvcHtmlString UpLoadNativeImage(this HtmlHelper htmlHelper, long ulid, string name, string value, string onchange = "LocalImagePreview(this)")
        {
            return htmlHelper.UpLoadNativeImage(new UpLoadSet { ULId = ulid, Name = name, Value = value }, onchange);
        }
        /// <summary>
        /// 原生图片上传控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="categoryCode">资源码</param>
        /// <param name="limitCode">限制码</param>
        /// <param name="name">隐藏的Name属性</param>
        /// <param name="value">隐藏的Value值</param>
        /// <param name="onchange"></param>
        /// <returns></returns>
        public static MvcHtmlString UpLoadNativeImage(this HtmlHelper htmlHelper, string categoryCode, string limitCode, string name, string value, string onchange = "LocalImagePreview(this)")
        {
            return htmlHelper.UpLoadNativeImage(new UpLoadSet { CategoryCode = categoryCode, LimitCode = limitCode, Name = name, Value = value }, onchange);
        }

        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="value">原上传路径</param>
        /// <param name="name">input的name属性</param>
        /// <returns></returns>
        public static string SaveFiles(this string value, string name)
        {
            return UploadExtension.SaveFiles(value, name.FormatSelf("{0}.File"), name.FormatSelf("{0}.Set"));
        }
        /// <summary>
        /// 上传文件保存
        /// </summary>
        /// <param name="name">input的name属性</param>
        /// <returns></returns>
        public static List<string> SaveFilesAsList(this string name)
        {
            return UploadExtension.SaveFilesAsList(name.FormatSelf("{0}.File"), name.FormatSelf("{0}.Set"));
        }
    }
}
